﻿Imports System.Net
Imports System.Text
Imports System.IO

Public Class HttpBrowser
    Inherits HttpBrowserBase

    Private Cookies As New CookieCollection

    Public Overrides Function SendRequest(ByVal URL As String, ByVal Method As MethodEnum, ByVal DumpID As String) As String
        Return (SendRequest(URL, Method, String.Empty, DumpID))
    End Function

    Public Overrides Function SendRequest(ByVal URL As String, ByVal Method As MethodEnum, ByVal Content As String, ByVal DumpID As String) As String

        Dim request = DirectCast(WebRequest.Create(URL), HttpWebRequest)

        request.ServicePoint.Expect100Continue = False
        'request.AllowAutoRedirect = True
        'request.PreAuthenticate = True
        'request.SendChunked = False

        request.CookieContainer = New CookieContainer()
        request.CookieContainer.Add(Cookies)

        Select Case Method
            Case MethodEnum.GetMethod
                request.Method = "GET"
            Case MethodEnum.PostMethod
                request.Method = "POST"
            Case Else
                Throw New Exception("Invalid method specified.")
        End Select

        If Content <> String.Empty Then

            request.ContentType = "application/x-www-form-urlencoded"
            Dim postdata = Encoding.ASCII.GetBytes(Content)
            request.ContentLength = postdata.Length
            Dim st = request.GetRequestStream

            st.Write(postdata, 0, postdata.Length)
            st.Close()

        End If

        Dim response = DirectCast(request.GetResponse, HttpWebResponse)
        Dim sr = New StreamReader(response.GetResponseStream)
        Dim responseBody = sr.ReadToEnd
        sr.Close()

        Cookies.Add(response.Cookies)

        Dim DumpStamp As String = Format(Now.Year, "0000") & Format(Now.Month, "00") & Format(Now.Day, "00") & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00") & "_" & DumpID

        If Debug Then DumpCookies(DumpStamp & "_cookies_pre")
        If Debug Then DumpResponse(DumpStamp & "_response", responseBody)

        If Debug Then DumpCookies(DumpStamp & "_cookies_post")

        'chiamo le delegate
        If Not PostRequestActions Is Nothing Then
            PostRequestActions.Invoke(responseBody)
        End If

        'restituisco
        Return responseBody

    End Function

    Public Overrides Sub DumpResponse(ByVal ID As String, ByVal Content As String)

        Dim sr As New StreamWriter(DebugFolder & "\" & ID & ".html")
        sr.Write(Content)
        sr.Close()

    End Sub

    Private Sub DumpCookies(ByVal ID As String)

        Dim sr As New StreamWriter(DebugFolder & "\" & ID & ".txt")

        For Each cookie In Cookies
            sr.WriteLine(cookie.ToString)
        Next

        sr.Close()

    End Sub

End Class
